<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Util\Tree;

class RbacController extends Controller
{
	//添加角色
	public function addRole()
	{
		$this->display();
	}
	
	//添加角色处理
	public function addRoleHandle(){
		
		if(M('Role')->add($_POST))
		{
			$this->success('添加成功!',U('rbac/addRole'));
		}
	}
	
	//角色管理（角色列表）
	public function roleList()
	{
		$this->role=M('Role')->select();
		$this->display();
	}
	
	//添加权限(节点)
	public function addNode()
	{
		$node=M('Node')->where('level!=3')->order('sort')->select();
		//dump($node);
		$this->assign('node',$node);

		$this->display();
	}
	
	//添加权限（节点）表单处理
	public function addNodeHandle()
	{
		$node=M('Node');
		$node->create();
		if($node->add())
		{
			$this->success('添加成功!',U('rbac/nodeList'));
		}
	}
	
		//权限管理（节点列表）
	public function nodeList()
	{
		//import('Common.Util.Tree');
		//$this->node=M('Node')->select();
		$node=M('node')->select();
		$this->node=Tree::create($node);
		//dump($this->node);
		$this->display();
	}
	
	//删除权限(节点)
	public function deleteNode()
	{
		if(M('Node')->where('id='.I('id','','int'))->delete())
		{
			$this->success('删除成功!',U('rbac/nodeList'));
		}
	}
	
	//添加用户
	public function addUser()
	{
		$role=M('Role')->select();
		$this->assign('role',$role);
		$this->display();

	}
	
	public function addUserHandle()
	{
		$data['username']=I('username');
		$data['password']=I('password');
		$data['last_login_time']=time();
		$data['last_login_ip']=get_client_ip();
		$data['status']=I('lock');
		$uid=M('user')->add($data);
		if($uid)
		{
			//用户添加成功后添加用户角色表
			$role['role_id']=I('role_id','','md5');
			$role['user_id']=$uid;
			M('role_user')->add($role);
			$this->success('添加成功!',U('rbac/userList'));
		}
		else
		{
			$this->error('添加失败！');
		}

	}
	
	//用户管理
	public function userList()
	{
		$this->user=D('User')->field('password',true)->relation(true)->select();
		//relation：使用关联模型，在Model文件夹先建立UserModel文件
		//dump($this->user);
		$this->display();
	}
	
	
	//权限管理
	public function access()
	{
		$id=I('id','','int');
		//$this->node=M('node')->order('sort')->select();
		$node=M('Node')->select();
		//$this->node=Tree::create($node);
		$this->node=$node;
		//dump($this->node);
		
		$data=array();//$data用于存放最新数组，里面包含当前用户组是否有相应权限
		$access=M('Access');
		foreach($node as $value)
		{
			$count=$access->where('role_id='.$id.' and node_id='.$value["id"])->count();
			//dump($count);
			if($count)
			{
				$value['access']=1;
			}
			else
			{
				$value['access']=0;
			}
			$data[]=$value;
		}
		//dump($data);
		$this->nodelist=Tree::create($data);
		//dump($this->nodelist);
		$this->id=$id;
		$this->name=M('Role')->getFieldById($id,'name');
		$this->display();
		
		
		
		
		
	}
	
	
	
}
?>